import { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message, Popconfirm } from 'antd';
import { useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { listMenu, addMenu, editMenu, deleteMenu, editMenuIsDisplay } from './menu';

const Menu: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [formValue, handleFormValue] = useState<Partial<ADMIN.Menu> | undefined>(undefined);
  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>();

  const handleUpdate = async (id: number | undefined, value: ADMIN.Menu) => {
    const hide = message.loading('正在修改');
    try {
      await editMenu(id, { ...value });
      hide();
      message.success('修改成功');
    } catch (err) {
      hide();
      message.error('修改失败');
    }
    handleUpdateModalVisible(false);
    actionRef.current?.reload();
    formRef.current?.resetFields();
  };

  const handleCreate = async (value: ADMIN.Menu) => {
    const hide = message.loading('正在添加');
    try {
      await addMenu({ ...value });
      hide();
      message.success('添加成功');
    } catch (err) {
      hide();
      message.error('添加失败');
    }
    handleCreateModalVisible(false);
    actionRef.current?.reload();
    formRef.current?.resetFields();
  };

  /**
   * @en-US delete menu
   * @zh-CN 删除菜单
   * @param fields
   */
  const handleDelete = async (id: number) => {
    const hide = message.loading('正在删除');
    try {
      await deleteMenu(id);
      hide();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败');
      return false;
    }
  };
  const renderDelete = (text: string, id: number) => (
    <Popconfirm
      key={`delete${id}`}
      title={`确认${text}吗?`}
      okText="是"
      cancelText="否"
      onConfirm={async () => {
        await handleDelete(id as number);
        actionRef.current?.reload();
      }}
    >
      <a>{text}</a>
    </Popconfirm>
  );

  const renderDisplay = (id: number, value: ADMIN.Menu) => (
    <>
      {value.display ? (
        <>
          <Popconfirm
            key={`hide${id}`}
            title={`确认隐藏吗?`}
            okText="是"
            cancelText="否"
            onConfirm={async () => {
              const displayValue = { display: 0 };
              await editMenuIsDisplay(id as number, displayValue);
              actionRef.current?.reload();
            }}
          >
            <a>隐藏</a>
          </Popconfirm>
        </>
      ) : (
        <>
          <Popconfirm
            key={`show${id}`}
            title={`确认显示吗?`}
            okText="是"
            cancelText="否"
            onConfirm={async () => {
              const displayValue = { display: 1 };
              await editMenuIsDisplay(id as number, displayValue);
              actionRef.current?.reload();
            }}
          >
            <a>显示</a>
          </Popconfirm>
        </>
      )}
    </>
  );

  const columns: ProColumns<ADMIN.Menu>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 50,
      valueType: 'indexBorder',
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '路由',
      dataIndex: 'route',
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      render: (_, record) => [
        renderDisplay(record.id, record),
        <a
          key={`edit${record.id}`}
          onClick={() => {
            handleUpdateModalVisible(true);
            handleFormValue(record);
          }}
        >
          编辑
        </a>,
        renderDelete('删除', record.id),
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<ADMIN.Menu>
        columns={columns}
        actionRef={actionRef}
        request={listMenu}
        rowKey="id"
        search={{
          collapsed: false,
          labelWidth: 'auto',
        }}
        pagination={{
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => handleCreateModalVisible(true)}>
            新建
          </Button>,
        ]}
      ></ProTable>
      <CreateForm
        createModalVisible={createModalVisible}
        handleCreateModalVisible={handleCreateModalVisible}
        handleCreate={handleCreate}
      ></CreateForm>
      <UpdateForm
        formValue={formValue || {}}
        updateModalVisible={updateModalVisible}
        handleUpdateModalVisible={handleUpdateModalVisible}
        handleUpdate={handleUpdate}
        formRef={formRef}
      ></UpdateForm>
    </PageContainer>
  );
};

export default Menu;
